﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Top.Api.Domain;
using Top.Api.Request;
using Top.Api.Response;
using Top.Api;
using System.Text;
using System.Runtime.InteropServices;
using IWshRuntimeLibrary;
using System.Data;
using DBControl;
using System.Security.Cryptography; 

namespace ZSZK
{
    public partial class _Default : Base
    {
        private static string appkey = System.Configuration.ConfigurationManager.AppSettings["AppKey"].ToString();
        private static string appsecret = System.Configuration.ConfigurationManager.AppSettings["AppSecret"].ToString();
        private static string appurl = System.Configuration.ConfigurationManager.AppSettings["AppUrl"].ToString();
        private static ITopClient client = new DefaultTopClient(appurl, appkey, appsecret);

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                VasSubscribeGetRequest vreq = new VasSubscribeGetRequest();
                vreq.Nick = Session["usNick"].ToString();
                vreq.ArticleCode = "ts-12715";
                VasSubscribeGetResponse vrep = client.Execute(vreq);
                ArticleUserSubscribe userlist = vrep.ArticleUserSubscribes.Find(delegate(ArticleUserSubscribe aus) { return aus.ItemCode == "ts-12715-5"; });
                if (userlist != null)
                {
                    ViewState.Add("maxuser", "10");
                    updatesub(userlist.Deadline);
                    getparentsub();
                    //userlist = vrep.ArticleUserSubscribes.Find(delegate(ArticleUserSubscribe aus) { return aus.ItemCode == "ts-12715-4"; });
                    //if (userlist != null)
                    //{
                    //    ViewState.Add("maxuser", "3");
                    //    updatesub(userlist.Deadline);
                    //    getparentsub();
                    //}
                    //else
                    //{
                    //    this.subusercontrol.Visible = false;
                    //    this.Panel1.Visible = true;
                    //}
                }
                else
                {
                    this.subusercontrol.Visible = false;
                    this.Panel1.Visible = true;
                }
                GetTreelist(Session["usNick"].ToString());
                Getgoodlist(null);
                bindchatter(Session["usNick"].ToString());
                
            }
        }

        /// <summary>
        /// 获取当前会话用户店铺的自定义列表
        /// </summary>
        /// <param name="usNick">当前会话用户昵称</param>
        /// <returns></returns>
        private void GetTreelist(string usNick)
        {
            SellercatsListGetRequest scListreq = new SellercatsListGetRequest();
            scListreq.Nick = usNick;
            scListreq.Fields = "cid,name,parent_cid,sort_order";
            SellercatsListGetResponse scListgetRes = client.Execute(scListreq);
            List<SellerCat> sclistParent = scListgetRes.SellerCats.FindAll(delegate(SellerCat scat) { return scat.ParentCid == 0; });
            List<SellerCat> sclistChildren = scListgetRes.SellerCats.FindAll(delegate(SellerCat scat) { return scat.ParentCid != 0; });

            TreeNode mtn = new TreeNode("所有宝贝", "all");
            this.cateTree.Nodes.Add(mtn);
            foreach (var item in sclistParent)
            {
                TreeNode tn = new TreeNode(item.Name, item.Cid.ToString());
                mtn.ChildNodes.Add(tn);
                foreach (var itemchild in sclistChildren)
                {
                    if (itemchild.ParentCid == item.Cid)
                    {
                        TreeNode tnchild = new TreeNode(itemchild.Name, itemchild.Cid.ToString());
                        tn.ChildNodes.Add(tnchild);
                    }
                }
            }
        }

        private void Getgoodlist(string cid,long pageno = 1)
        {
            ItemsOnsaleGetRequest onsellreq = new ItemsOnsaleGetRequest();
            onsellreq.Fields = "num_iid,title,price,pic_url";
            onsellreq.PageSize = this.AspNetPager.PageSize;
            onsellreq.PageNo = pageno;
            if (cid != null)
            {
                onsellreq.SellerCids = cid;
            }
            ItemsOnsaleGetResponse onSellRes = client.Execute(onsellreq, Session["sessionKey"].ToString());
            this.goodlist.DataSource = onSellRes.Items;
            this.goodlist.DataBind();
            this.AspNetPager.RecordCount = int.Parse(onSellRes.TotalResults.ToString());
        }

        protected void AspNetPager_PageChanged(object sender, EventArgs e)
        {
            if (ViewState["searchkeyword"] != null)
            {
                bindsearch(this.AspNetPager.CurrentPageIndex);
            }
            else
            {
                Getgoodlist(this.cateTree.SelectedValue, this.AspNetPager.CurrentPageIndex);
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "resizeImg", "<script>resizeImg()</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "onloadfun", "<script>onloadfun();</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "opendialog", "<script>opendialog();</script>", false);
        }

        protected void cateTree_SelectedNodeChanged(object sender, EventArgs e)
        {
            ViewState.Clear();
            
            if (this.cateTree.SelectedValue == "all")
            {
                Getgoodlist(null);
            }
            else
            {
                Getgoodlist(this.cateTree.SelectedValue);
            }
            this.AspNetPager.CurrentPageIndex = 1;
            ScriptManager.RegisterStartupScript(this, this.GetType(), "resizeImg", "<script>resizeImg()</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "onloadfun", "<script>onloadfun();</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "opendialog", "<script>opendialog();</script>", false);
        }

        private void bindchatter(string usNick)
        {
            WangwangEserviceChatpeersGetRequest req = new WangwangEserviceChatpeersGetRequest();
            req.ChatId = "cntaobao" + usNick;
            req.StartDate = DateTime.Now.Date.ToString("yyyy-MM-dd");
            req.EndDate = DateTime.Now.Date.ToString("yyyy-MM-dd");
            WangwangEserviceChatpeersGetResponse response = client.Execute(req, Session["sessionKey"].ToString());
            if (!response.IsError)
            {
                var pn = (from m in response.Chatpeers
                          orderby m.Date descending
                          select m).Take(10).ToList<Chatpeer>();
                ListItem nli = new ListItem("");
                this.chatter.Items.Add(nli);
                foreach (var item in pn)
                {
                    ListItem li = new ListItem(item.Uid.Replace("cntaobao", ""));
                    this.chatter.Items.Add(li);
                }
            }
            else
            {
            }
        }

        protected void deltag_Click(object sender, EventArgs e)
        {

        }

        protected void search_Click(object sender, EventArgs e)
        {
            if (this.keyword.Text == "")
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alerterror", "<script>alert('请输入查询宝贝的标题!')</script>", false);
            }
            else
            {
                if (this.cateTree.SelectedNode != null)
                {
                    this.cateTree.SelectedNode.Selected = false;
                }
                ViewState.Add("searchkeyword", this.keyword.Text.Trim());
                bindsearch();
                this.AspNetPager.CurrentPageIndex = 1;
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "resizeImg", "<script>resizeImg()</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "onloadfun", "<script>onloadfun();</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "opendialog", "<script>opendialog();</script>", false);
        }

        private void bindsearch(long pageno = 1)
        {
            ItemsGetRequest itemsreq = new ItemsGetRequest();
            itemsreq.Fields = "num_iid,title,price,pic_url";
            itemsreq.Q = ViewState["searchkeyword"].ToString();
            itemsreq.PageSize = this.AspNetPager.PageSize;
            itemsreq.Nicks = Session["usNick"].ToString();
            itemsreq.PageNo = pageno;
            ItemsGetResponse itemsrep = client.Execute(itemsreq);
            this.goodlist.DataSource = itemsrep.Items;
            this.goodlist.DataBind();
            this.AspNetPager.RecordCount = int.Parse(itemsrep.TotalResults.ToString());
            //this.AspNetPager.CurrentPageIndex
        }

        private void getparentsub()
        {
            string getsubuser = "SELECT * FROM UserSession WHERE ParentNick = '" + Session["usNick"] + "'";
            SqlDbHelper sdh = new SqlDbHelper();
            DataTable table = sdh.ExecuteDataTable(getsubuser);
            this.subusercontrol.DataSource = table;
            this.subusercontrol.DataBind();

            int allcount = int.Parse(ViewState["maxuser"].ToString()) - table.Rows.Count;
            this.subcount.Text = "您已经添加了" + table.Rows.Count + "个子账号，还可以添加" + allcount.ToString() + "个子账号";
        }

        private void updatesub(string overtime)
        {
            string updatesub = "UPDATE UserSession SET UpdateTime='" + overtime + "' WHERE ParentNick = '" + Session["usNick"] + "'";
            SqlDbHelper sdh = new SqlDbHelper();
            sdh.ExecuteNonQuery(updatesub);
            this.deadline.Value = overtime;
        }

        protected void subusercontrol_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            LinkButton linktemp = (LinkButton)e.CommandSource as LinkButton;
            SqlDbHelper sdh = new SqlDbHelper();
            switch (e.CommandName)
            {
                case "delete":
                    string delsubuser = "DELETE UserSession WHERE UsId = '" + e.CommandArgument + "'";
                    try
                    {
                        sdh.ExecuteNonQuery(delsubuser);
                        getparentsub();
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    break;
                case "download":
                    Label nalab = linktemp.Parent.FindControl("sublab") as Label;
                    Response.Redirect("/AjaxCommand/subShortcut.ashx?subname=" + nalab.Text + "&loginsubindex=" + e.CommandArgument);
                    break;
                case "new":
                    int subcount = this.subusercontrol.Items.Count;
                    if (subcount >= int.Parse(ViewState["maxuser"].ToString()))
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "<script>alert('您的子账号数已达到最大值!')</script>", false);
                        break;
                    }
                    DropDownList ddl = linktemp.Parent.FindControl("newsubddl") as DropDownList;
                    TextBox tx = linktemp.Parent.FindControl("newmaxmoney") as TextBox;
                    string loginsubindex = HashString(Encoding.UTF8, ddl.SelectedItem.Value.Trim() + Session["usNick"]);
                    string insertsql = "INSERT INTO UserSession(UsID,UsNick,SessionKey,UpdateTime,ParentNick,maxmoney,loginsubindex)VALUES(" + ddl.SelectedItem.Value + ",'" + ddl.SelectedItem.Text + "','" + Session["sessionKey"] + "','"+ this.deadline.Value +"','" + Session["usNick"] + "'," + tx.Text + ",'"+ loginsubindex +"');";
                    try
                    {
                        sdh.ExecuteNonQuery(insertsql);
                        getparentsub();
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    break;
                case "edit":
                    linktemp.Visible = false;
                    linktemp.Parent.FindControl("maxmoneylab").Visible = false;
                    linktemp.Parent.FindControl("dellink").Visible = false;
                    linktemp.Parent.FindControl("maxmoney").Visible = true;
                    linktemp.Parent.FindControl("enterlink").Visible = true;
                    linktemp.Parent.FindControl("cancellink").Visible = true;
                    break;
                case "cancel":
                    linktemp.Visible = false;
                    linktemp.Parent.FindControl("maxmoneylab").Visible = true;
                    linktemp.Parent.FindControl("dellink").Visible = true;
                    linktemp.Parent.FindControl("editlink").Visible = true;
                    linktemp.Parent.FindControl("maxmoney").Visible = false;
                    linktemp.Parent.FindControl("enterlink").Visible = false;
                    break;
                case "enter":
                    TextBox txmoney = linktemp.Parent.FindControl("maxmoney") as TextBox;
                    string updatesubuser = "UPDATE UserSession SET maxmoney=" + txmoney.Text.Trim() + " WHERE UsID = '" + e.CommandArgument + "'";
                    try
                    {
                        sdh.ExecuteNonQuery(updatesubuser);
                        getparentsub();
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    break;
                default:
                    break;
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "resizeImg", "<script>resizeImg()</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "onloadfun", "<script>onloadfun();</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "opendialog", "<script>opendialog();</script>", false);
        }

        protected void subusercontrol_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if (DataBinder.Eval(e.Item.DataItem, "UsNick").ToString() != "")
                {
                    LinkButton dellink = (LinkButton)e.Item.FindControl("dellink");
                    LinkButton editlink = (LinkButton)e.Item.FindControl("editlink");
                    LinkButton enterlink = (LinkButton)e.Item.FindControl("enterlink");
                    dellink.Attributes.Add("onclick", "return delsubuser('" + DataBinder.Eval(e.Item.DataItem, "UsNick") + "',this)");
                    enterlink.Attributes.Add("onclick", "return editsubuser(this)");
                    dellink.Visible = true;
                    editlink.Visible = true;
                }
            }
            else if (e.Item.ItemType == ListItemType.Footer)
            {
                DropDownList ddl = (DropDownList)e.Item.FindControl("newsubddl");
                ListItem dli = new ListItem("", "");
                ddl.Items.Add(dli);
                SellercenterSubusersGetRequest subuserreq = new SellercenterSubusersGetRequest();
                subuserreq.Nick = Session["usNick"].ToString();
                SellercenterSubusersGetResponse subuserrep = client.Execute(subuserreq, Session["sessionKey"].ToString());
                SqlDbHelper sdh = new SqlDbHelper();
                string getsubuser = "SELECT UsID FROM UserSession WHERE ParentNick = '" + Session["usNick"] + "'";
                DataTable dt = sdh.ExecuteDataTable(getsubuser);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    SubUserInfo si = subuserrep.Subusers.Find(delegate(SubUserInfo sub) { return sub.SubId.Equals(long.Parse(dt.Rows[i]["UsID"].ToString())); });
                    if (si != null)
                    {
                        subuserrep.Subusers.Remove(si);
                    }
                }
                foreach (var item in subuserrep.Subusers)
                {
                    if (item.Status == 1)
                    {
                        ListItem sublist = new ListItem(item.Nick, item.SubId.ToString());
                        ddl.Items.Add(sublist);
                    }
                }
                LinkButton newlink = (LinkButton)e.Item.FindControl("newlink");
                newlink.Attributes.Add("onclick", "return checknewsub(this)");
            }
        }



        /// <summary> 
        /// 使用指定的编码将字符串散列 
        /// </summary> 
        /// <param name="encode">编码</param> 
        /// <param name="sourceString">要散列的字符串</param> 
        /// <returns>散列后的字符串</returns> 
        private string HashString(Encoding encode, string sourceString)
        {
            MD5 md5 = MD5.Create();
            byte[] source = md5.ComputeHash(encode.GetBytes(sourceString));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < source.Length; i++)
            {
                sBuilder.Append(source[i].ToString("x"));
            }
            return sBuilder.ToString();
        }
    }
}